<template>
  <div class="script-wrapper">
    <a-drawer :visible="visible" title="云成片库" placement="right" destroyOnClose  width="1250" @close="cancelClick">
      <a-spin tip="正在上传中..." :spinning="spinningUpload">
        <div style="position: relative;">
          <a-radio-group v-model:value="Library_value" style="margin-bottom: 20px">
              <a-radio-button value="1">系统剪辑成片</a-radio-button>
              <a-radio-button value="2">自主上传成片</a-radio-button>
            </a-radio-group>
            <div style="margin-left: 20px; position: absolute;  top: 5px; left: 242px;">
                  已选择  <span
                        style="
                          height: 100%;
                          border-radius: 5px;
                          background-color: var(--ss-primary-color);
                          color: #fff;
                          padding: 0 5px;
                        "
                      >{{ isSelected.length }}</span> 个成片
            </div>
        </div>
    
        <section class="content-box">
          <a-row justify="space-between" align="middle" style="margin-bottom: 20px">
            <div style="display: flex; gap: 10px;">
              <a-col>
                <a-input v-model:value="material_name" placeholder="请输入需要的成片名称">
                  <template #prefix>
                    <search-outlined />
                  </template>
                </a-input>
              </a-col>
              <a-col>
                <a-select style="width: 200px;" v-model:value="merchantLibraryId" show-search :filter-option="false"
                  allowClear @change="onSelectLibrary" placeholder="请选择项目" :options="libraryList">
                  <template v-if="fetching" #notFoundContent>
                    <a-spin size="small" />
                  </template>
                </a-select>
              </a-col>

              <a-col v-show="!!merchantLibraryId">
                <a-select style="width: 200px;" v-model:value="folder_id" show-search :filter-option="false" allowClear
                  @change="serchChange" placeholder="请选择文件夹" :options="folderList">
                  <template v-if="fetching" #notFoundContent>
                    <a-spin size="small" />
                  </template>
                </a-select>
              </a-col>

              <!-- 只有剪辑成片才允许搜索 -->
              <a-col v-show="Library_value != 2">
                <a-select style="width: 200px;" v-model:value="editing_record_id" show-search :filter-option="false"
                  allowClear @change="serchChange" placeholder="请选择混剪项" :options="editingList">
                  <template v-if="fetching" #notFoundContent>
                    <a-spin size="small" />
                  </template>
                </a-select>
              </a-col>

            </div>
            <a-col>
              <a-row align="middle" v-if="not_use_release_num > 0 && status != 1">
                <a-col>快捷选择：</a-col>
                <a-col>
                  <a-input-number v-model:value="quickNum" placeholder="请输入" :min="0" :max="not_use_release_num"
                    @blur="quickNumBlur" style="width: 120px; margin-right: 5px" addon-after="个" />
                </a-col>
                <a-col>共{{ not_use_release_num }}个可使用成片</a-col>
              </a-row>
            </a-col>
          </a-row>
          <div style="margin-bottom: 20px;padding-right:20px; display: flex; align-items: center; justify-content: space-between;">
            <a-radio-group v-model:value="status" @change="statusChange">
              <a-radio-button :value="-1">全部（{{ all_num }}）</a-radio-button>
              <a-radio-button :value="0">未使用（{{ not_use_release_num }}）</a-radio-button>
              <a-radio-button :value="1">已使用（{{ use_release_num }}）</a-radio-button>
            </a-radio-group>
            <Upload  v-if="Library_value =='2'" @loadingUpload="loadingUpload"/>
          </div>


          <a-spin tip="加载中..." :spinning="spinning">
            <section style="height: 630px; overflow: hidden auto">
              <a-row :gutter="[16, 16]" v-if="filmVideoList.length">
                <a-col :span="4" v-for="(item, index) in filmVideoList" :key="item.id">
                  <div class="content">
                    <div class="media-box">
                      <!-- <div class="is_used" v-if="item?.image_ary">{{item?.is_used?'已使用':'未使用'}}</div> -->

                      <div class="image_type_icon" v-if="item?.image_ary">
                        图集
                        <cu-icon class="icon" type="icon-tupian2" style="font-size: 14px; cursor: pointer" />
                      </div>

                      <div class="image_type_icon" v-else>
                        视频
                        <cu-icon class="icon" type="icon-play" style="font-size: 14px; cursor: pointer" />
                      </div>

                      <div class="image_num" v-if="item?.image_ary">
                        图片数量：{{ item.image_ary?.length }}
                      </div>

                      <img v-if="item?.image_ary" :src="item?.image_ary[0]" alt="" />

                      <img v-if="item.cover_url && item.cover_url !==''" :src="item.cover_url" alt="" style="width: 100%; height: 285px" />

                      <div v-if="!item.cover_url && !item?.image_ary" style="width: 100%; height: 285px; overflow: hidden;">
                          <img :src="default_corver" alt="" style="width: 100%; height: 100%;  object-fit: cover; 
                              transform: scale(1.8); transform-origin: center;" >
                      </div>
                      
                    </div>
                    <div class="single-line">
                      {{ item.material_name }}
                    </div>
                    <!-- @click.stop="item.checked = !item.checked" -->
                    <div class="image-mask" @click.stop="change_checked(item, index)">
                      <cu-icon class="icon" type="icon-shipin" @click.stop="previewImg(item)" />
                    </div>
                    <a-row class="count-info" justify="space-between" align="middle" @click.stop="change_checked(item, index)">
                      <a-col :span="12">
                        <a-checkbox v-model:checked="item.checked" :disabled="item.disabled"
                          v-if="item.use_release !== 1" />
                      </a-col>
                      <a-col :span="12" style="text-align: right">
                        <!-- <a-tag
                          style="{
                            color: item.use_release === 0 ? '#f50' : '#87d068',
                          }"
                        >
                          {{ item.use_release == 0 ? "未使用" : "已使用" }}</a-tag
                        > -->
                        <a-tag v-if="item.use_release == 0" style="
                            color: #389e0d;
                            background: #f6ffed;
                            border-color: #b7eb8f;
                          ">未使用</a-tag>
                        <a-tag v-if="item.use_release == 1" style="
                            color: #cf1322;
                            background: #fff1f0;
                            border-color: #ffa39e;
                          ">已使用</a-tag>
                      </a-col>
                    </a-row>
                  </div>
                </a-col>
              </a-row>
              <a-empty v-else :image="simpleImage" />
            </section>
          </a-spin>
        </section>
     </a-spin>

      <template #footer>
        <a-row justify="space-between">
          <a-col>
            <div class="left" style="display: flex; align-items: center;">
  <a-pagination v-model:current="page" :disabled="spinningUpload" :pageSize="pageSize" :total="total" @change="onPaginationChange"  show-size-changer
              show-less-items />

         
              
            </div>
          
          </a-col>
          <a-col>


            <a-button style="margin-right: 8px" @click="cancelClick">取消</a-button>
            <a-button :disabled="spinningUpload" type="primary" @click="confirmClick">确定</a-button>
          </a-col>
        </a-row>
      </template>
    </a-drawer>

    <!-- 预览 -->
    <PreviewModal :visible="visibleImage" @onCancel="visibleImage = false" :url="previewImgUrl" :title="previewTitle"
      :type="typeChange" />
    <swiperPreview :visible="swiperVisible" :coverArr="imageArr" @close="(swiperVisible = false), (imageArr = [])" />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, watch, computed } from "vue";
import { SearchOutlined } from "@ant-design/icons-vue";
import swiperPreview from "../../MaterialCenter/swiperPreview.vue";
import request from "../../../../common/utils/request";
import PreviewModal from "../../../../components/PreviewModal/index.vue";
import { EyeFilled ,PlusOutlined} from "@ant-design/icons-vue";
import { Empty, message } from "ant-design-vue";
import { useRoute } from "vue-router";
import { nextTick } from "vue";
import utils from '@/common/utils/utils.js'
import Upload from "../../components/Upload/index.vue"

export default defineComponent({
  name: "CloudImageLibrary",
  components: {
    SearchOutlined,
    PreviewModal,
    EyeFilled,
    swiperPreview,
    PlusOutlined,
    Upload
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    imgeUrl: {
      type: String,
      default: "",
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    filmVideoIds: {
      type: Array,
      default: () => {
        return [];
      },
    },
    new_filmVideoList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    poiKey: {
      type: [Number, String],
      default: 0,
    },
    selectVideoList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    film_type: {
      type: [Number, String],
      default: 1,
    },
    film_platform: {
      type: String,
      default: '',
    },
    // 项目列表
    libraryList: {
      type: Array,
      default: []
    },
    // 混剪列表
    editingList: {
      type: Array,
      default: []
    }
  },
  setup(props, { emit }) {
    const state = reactive({
       default_corver:  utils.staticPath + "images/workAi/shotstack/default_corver.png",
      count: 0,
      name: "",
      status: -1, //筛选是否已使用，-1 全部，0 未使用，1 已使用
      page: 1,
      pageSize: 20,
      total: 0,
      visibleImage: false,
      previewImgUrl: "",
      typeChange: "video",
      previewTitle: "",
      filmVideoList: [],
      filmVideoAll: [],
      // 项目名称和id
      material_name: "",
      merchantLibraryId: null,
      // 文件夹id
      folder_id: null,
      // 混剪项目id
      editing_record_id: null,
      spinning: false,
      quickNum: "",
      notUsedList: [],
      usedList: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      swiperVisible: false,
      imageArr: [],
      Library_value: "1",
      all_num: 0,
      not_use_release_num: 0,
      use_release_num: 0,
      // 文件夹列表
      folderList: [],
      isSelected: [],
      spinningUpload:false
    });
    const route = useRoute();
    const getFilmVideoList = () => {

      let params = {
        merchantLibraryId: state.merchantLibraryId || undefined,
        material_name: state.material_name || undefined,
        folder_id: state.folder_id || undefined,
        editing_record_id: state.editing_record_id || undefined,
        page: state.page,
        pageSize: state.pageSize,
        folder_type: props.film_type == 1 ? "video" : "image",
        from: state.Library_value == "2" ? "film" : "",
        platform: route.query.platform,
        use_release: state.status,
      };
      if (props.film_platform && ! params['platform']) {
        params['platform'] = props.film_platform;
      }
      state.spinning = true;
      request
        .get("/work_ai", "/user/shotstack/filmVideo/list", params)
        .then((res) => {
           state.filmVideoList = res.result.data.map(item => ({
             ...item,
             checked: false
           }));
          state.all_num = res.num.all_num; //全部数量
          state.not_use_release_num = res.num.not_use_release_num; //未使用数量
          state.use_release_num = res.num.use_release_num; //已使用数量
          state.total = res.result.total; //总数
          // 选择回显
          if (props.selectVideoList.length) {
            let videoIds = [];
            props.selectVideoList.forEach((item) => {
              if (item.video_list.length) {
                item.video_list.forEach((video) => {
                  videoIds.push({
                    store_id: item.store_id,
                    id: video.id,
                  });
                });
              }
            });
            state.filmVideoList.forEach((item) => {
              if (videoIds.length) {
                videoIds.forEach((video) => {
                  if (item.id == video.id) {
                    item.checked = true;
                    item.store_id = video.store_id;
                  }
                });
              }
            });
          }
          if (props.filmVideoIds.length) {
            state.filmVideoList.forEach((item) => {
              props.filmVideoIds.forEach((film) => {
                if (item.id == film) {
                  item.checked = true;
                }
              });
            });
          }
          // 过滤出已使用和未使用的
          state.filmVideoList.forEach((item) => {
            if (item.store_id && props.poiKey !== item.store_id) {
              item.disabled = true;
            }
          });

          if ( state.isSelected.length > 0) {
            state.isSelected.forEach((v1, index1) => {
              state.filmVideoList.forEach((v2, index2) => {
                if (v1.id == v2.id) {
                  state.filmVideoList[index2].checked = true
                }
              })
             })
          }


          state.spinning = false;
        })
        .catch(() => {
          state.spinning = false;
        });
    };

    const onPaginationChange = (page, pageSize) => {
      // state.filmVideoList.forEach(item => {
      //   if (item.checked && !state.isSelected.find(selectedItem => selectedItem.id === item.id)) {
      //     state.isSelected.push(item);
      //   }
      // });

      state.page = page;
      state.pageSize = pageSize;
      getFilmVideoList();
    };

    // 快捷选择
    const quickNumBlur = () => {
      if (state.quickNum > state.pageSize) {
        message.warn("当前页面最多20条, 可调整分页数")
      }

      
      state.filmVideoList
        ?.filter((ele) => ele.use_release == 0)
        ?.forEach((item, index) => {
          if (index <= state.quickNum - 1) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        });
     state.filmVideoList.forEach(item => {
         if (item.checked && !state.isSelected.some(selectedItem => selectedItem.id === item.id)) {
             state.isSelected.push(item);
         }
     });
    };

    const previewImg = (data) => {
      if (data?.image_ary && data?.image_ary?.length) {
        state.swiperVisible = true;
        state.imageArr = data?.image_ary;
        return;
      }
      state.previewImgUrl = data.material_url;
      state.typeChange = data.material_type;
      state.previewTitle = data.material_name;
      state.visibleImage = true;
    };

    watch(
      () => state.Library_value,
      (val) => {
        state.folder_id = null
        state.merchantLibraryId = null
        state.editing_record_id = null
        getFilmVideoList();
      },
      {
        //  immediate: true,
        //  deep: true
      }
    );
    const statusChange = () => {
      getFilmVideoList();
    };
    watch(
      () => state.material_name,
      (val) => {
        getFilmVideoList();
      }
    );
    // 重置搜索数据
    const initSerchData = () => {
      state.material_name = ''
      state.merchantLibraryId = null
      state.folder_id = null
      state.editing_record_id = null
    };
    const cancelClick = () => {
      state.isSelected = []
      state.spinningUpload = false
      emit("onCancel");
      initSerchData()
    };

    const confirmClick = () => {
      let list = [];
      if (props.poiKey) {
        list = state.isSelected.filter(
          (item) =>
            (item.checked && item.use_release == 0 && !item.store_id) ||
            (!item.checked &&
              item.use_release == 0 &&
              item.store_id == props.poiKey)
        );
      } else {
      console.log(state.isSelected,   '已选中的数组');

        list = state.isSelected.filter(
          (item) => item.checked && item.use_release == 0
        );
      }

      console.log(list,   '传出去的数组11111');

      emit("onConfirm", list);
      initSerchData()
      state.isSelected = []
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getFilmVideoList();

          getchecked()
        }
      }
    );

    // 获取成片文件夹列表
    const getFolderList = async (merchant_library_id) => {
      const find = props.libraryList.find(item => item.value == merchant_library_id)
      const params = {
        folder_use_type: 2,
        material_type: 'video',
        merchant_library_id,
        group_id: find.default,
      }
      const res = await request.post("/work_ai", "/user/shotstack/folder/list", params);
      console.log(res.result, '文佳佳');
      if (res.result.data.length) {
        state.folderList = res.result.data.map((item) => {
          return {
            label: item.folder_name,
            value: item.id,
          };
        });


      }
    }

    const getchecked = () => {
      props.new_filmVideoList.forEach(data => {
        state.isSelected.push(data)
      })
      state.isSelected.forEach(item => {
        if (item.material_id) {
          item.id = item.material_id
        }
      })

     // 使用 map 方法遍历并更新每一项
state.isSelected = state.isSelected.map(item => {
  const newItem = { ...item };

  if (!('checked' in item)) {
    newItem.checked = true;
  }

  if (!('use_release' in item)) {
    newItem.use_release = 0;
  }

  return newItem;
});

    }

const change_checked = (data, index) => {
  const itemId = data.id;

  // 更新选中状态
  state.filmVideoList[index].checked = !state.filmVideoList[index].checked;
  const itemIndex = state.isSelected.findIndex(item => item.id === itemId);

  if (state.filmVideoList[index].checked) {
    if (itemIndex === -1) {
      state.isSelected.push(data);
    }
  } else {
    if (itemIndex > -1) {
      state.isSelected.splice(itemIndex, 1);
    }
  }
    };







    const onSelectLibrary = (val) => {

      nextTick(() => {
        getFilmVideoList();
        if (val) {
          getFolderList(val)
        } else {
          state.folderList = []
        }
      })
    }

    const serchChange = () => {
      getFilmVideoList();
    }


    const loadingUpload=(val)=>{
        if(val){
           state.spinningUpload = true
        }else{
           state.spinningUpload =  false
          setTimeout(()=>{
            getFilmVideoList();
          },10)
        }
    }

    return {
      ...toRefs(state),
      cancelClick,
      confirmClick,
      serchChange,
      previewImg,
      onPaginationChange,
      quickNumBlur,
      onSelectLibrary,
      initSerchData,
      route,
      statusChange,
      change_checked,
      loadingUpload
    };
  },
});
</script>

<style lang="less">
// .script-wrapper {
//   :deep(.ss-drawer-body) {
//     padding: 24px 24px 0 24px !important;
//   }
// }

.ss-drawer-body {
 padding: 24px 24px 0 24px !important;
}
</style>

<style lang="less" scoped>
.content-box {
  width: 100%;
  height: calc(100% - 52px);
  overflow: hidden auto;

  .content {
    width: 100%;
    position: relative;

    .media-box {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      position: relative;
      background-color: #000;

      img {
        max-width: 100%;
        max-height: 100%;
      }

      .is_used {
        position: absolute;
        right: 10px;
        top: 10px;
        color: #fff;
      }

      .image_num {
        position: absolute;
        left: 10px;
        bottom: 5px;
        color: #fff;
      }

      .image_type_icon {
        position: absolute;
        left: 10px;
        bottom: 30px;
        color: #fff;
      }
    }

    .image-mask {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 285px;
      border-radius: 4px;
      background: rgba(0, 0, 0, 0.4);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      opacity: 0;
      color: #fff;

      .icon {
        font-size: 45px;
      }

      .icon-eye-filled {
        font-size: 24px;

        &:hover {
          color: #2878ff;
        }
      }
    }

    .use_release {
      color: red;
      background: #d0d0d0;
      border-radius: 5px;
      padding: 2px 4px;
      font-weight: 500;
    }

    &:hover {
      .image-mask {
        opacity: 1;
      }
    }

    .bg-content {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 285px;
      border-radius: 4px;
      background: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      z-index: 99;
    }

    .count-info {
      position: absolute;
      top: 5px;
      left: 0;
      width: 100%;
      padding: 0 5px;

      .text {
        padding: 0px 5px;
        color: #fff;
        border-radius: 2px;
        background: rgba(0, 0, 0, 0.4);
      }
    }
  }

  .single-line {
    width: 100%;
    /* 根据需求调整宽度 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}



</style>
